<template>
  <div>
    <div class="room-box" v-if="!store.isRoomFlag">
      <div class="room-box-logo">
        <lottie-animation
          :animationData="animationData"
          :loop="true"
          :autoplay="true"
        ></lottie-animation>
      </div>
      <div class="room-box-btns">
        <van-row>
          <van-cell>
            <van-button
              round
              type="default"
              size="large"
              @click="addFlag = true"
            >
              <font-awesome-icon :icon="['fa', 'plus']" />
              &nbsp;创 建</van-button
            >
          </van-cell>
          <van-cell>
            <van-button
              round
              type="primary"
              size="large"
              @click="joinFlag = true"
            >
              <font-awesome-icon :icon="['fa', 'paper-plane']" />
              &nbsp;加 入</van-button
            ></van-cell
          >
          <van-cell>
            <van-button round type="primary" size="large" @click="handleJoinAI">
              <font-awesome-icon :icon="['fa', 'robot']" />
              &nbsp;AI对话</van-button
            ></van-cell
          >
        </van-row>
      </div>
      <div class="room-box-bg">
        <lottie-animation
          :animationData="animationBg"
          :loop="true"
          :autoplay="true"
        ></lottie-animation>
      </div>
    </div>

    <chat-list
      v-if="store.isRoomFlag && !setFlag"
      :roomInfo="store.roomInfo"
      @right="handleSet"
      @leave="handleLeave"
      :userInfo="userInfo"
    ></chat-list>

    <van-dialog
      v-model:show="addFlag"
      title="创建房间"
      show-cancel-button
      :before-close="handleClose"
      @confirm="handleAdd"
      close-on-click-overlay
    >
      <van-form :model="addForm" ref="addRef">
        <van-cell-group inset>
          <van-field
            v-model.trim="addForm.roomNo"
            name="房间号"
            label="房间号"
            placeholder="请输入房间号"
            :rules="[{ required: true, message: '请填写房间号' }]"
          />
          <van-field
            v-model.trim="addForm.roomName"
            name="房间名"
            label="房间名"
            placeholder="请输入房间名"
            :rules="[{ required: true, message: '请填写房间名' }]"
          />
        </van-cell-group>
      </van-form>
    </van-dialog>

    <!--房间设置-->
    <van-popup
      closeable
      v-model:show="setFlag"
      position="right"
      :style="{ width: '100%', height: '100%', background: '#F5F4F5' }"
    >
      <van-cell-group inset style="margin-top: 50px">
        <van-cell title="全部成员" />
        <van-row :gutter="10" style="padding: 10px 16px; min-height: 100px">
          <van-col
            span="6"
            v-for="(item, index) in store.personList"
            :key="index"
          >
            <div class="person-info-box">
              <chat-image round width="50px" height="50px" :src="item.avatar" />
              <span
                style="width: 100%; padding: 0px 8px; text-align: center"
                class="ellipsisText"
                >{{ item.userName }}</span
              >
            </div>
          </van-col>
        </van-row>
      </van-cell-group>
      <van-cell-group inset style="margin-top: 10px">
        <van-cell title="房间名称" :value="store.roomInfo.roomName" />
        <van-cell title="房间号" :value="store.roomInfo.roomNo" />
        <van-cell title="房间描述" value="-" />
      </van-cell-group>
      <van-cell-group
        inset
        style="margin-top: 10px; text-align: center; padding: 10px 16px"
      >
        <van-button color="#316BFF" type="primary" @click="handleLeave"
          >退出房间</van-button
        >
      </van-cell-group>
    </van-popup>

    <van-dialog
      v-model:show="joinFlag"
      title="加入房间"
      confirm-button-text="加 入"
      :show-cancel-button="false"
      :before-close="handleClose"
      @confirm="handleJoin"
      close-on-click-overlay
    >
      <van-form :model="joinForm" ref="joinRef">
        <van-cell-group inset>
          <van-field
            v-model.trim="joinForm.roomNo"
            name="房间号"
            label="房间号"
            placeholder="请输入房间号"
            :rules="[{ required: true, message: '请填写房间号' }]"
          />
        </van-cell-group>
      </van-form>
    </van-dialog>
  </div>
</template>  
<script lang="ts">
import {
  defineComponent,
  reactive,
  toRefs,
  getCurrentInstance,
  onMounted,
} from "vue";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox } from "element-plus";
import { useSocket } from "@/utils/socket/useSocket";
import MySender from "@/utils/socket/MySender";
import MsgCommand from "@/utils/socket/enums/MsgCommand";
import { getRoomList } from "@/api/room";
import userStore from "@/store/user";
import chatList from "./src/chatList.vue";
import animationLogo from "@/animation/chat.json";
import animationBg from "@/animation/bg.json";
import { getUser } from "@/api/user";
import { showToast, showConfirmDialog } from "vant";
export default defineComponent({
  props: {},
  components: {
    chatList,
  },
  setup(props: any, { emit }: any) {
    const state = reactive({
      loading: false,
      sendInfo: {
        text: "",
      },
      socketClient: {},

      messageList: [],

      joinFlag: false,
      addFlag: false,
      addForm: {
        roomNo: "",
        roomName: "",
        userId: "",
      },
      joinForm: {
        roomNo: "",
      },
      animationData: animationLogo,
      animationBg: animationBg,
      chatFlag: false,
      activeChatClass: "",
      userInfo: {},
      setFlag: false,
    });
    const { proxy } = getCurrentInstance() as any;

    const { initSocketFun, chatStatus } = useSocket();

    const store = userStore();

    onMounted(() => {
      // setTimeout(() => {
      //   handleLogin();
      // }, 1000);
    });

    // const login = () => {
    //   send("UserLogin", { userId: state.userId });
    // };

    /**
     * 离开房间
     */
    const handleLeave = () => {
      showConfirmDialog({
        title: "提示",
        message: "确认要离开房间吗？",
        cancelButtonText: "否",
        confirmButtonText: "是",
      })
        .then(() => {
          state.setFlag = false;
          // on confirm
          MySender.getInstance().sendMsg(MsgCommand.LEAVE_ROOM, {
            roomId: store.roomInfo.roomId,
          });
        })
        .catch(() => {
          // on cancel
        });
    };

    // 登录后和系统数据同时销毁存在
    const openSocket = (userInfo: any) => {
      state.addForm.userId = userInfo.userId;
      state.userInfo = userInfo;
      initSocketFun(userInfo);
    };

    const loadRoomList = async () => {
      const res = await getRoomList({});
    };

    const handleAdd = () => {
      proxy.$refs.addRef.validate().then((valid: any) => {
        MySender.getInstance().sendMsg(MsgCommand.CREATE_ROOM, state.addForm);
        setTimeout(() => {
          state.addFlag = false;
        }, 100);
      });
    };

    const handleLogin = () => {
      MySender.getInstance().sendMsg(MsgCommand.USER_LOGIN, {
        userId: state.addForm.userId,
        userName: state.userInfo.userName,
        avatar: state.userInfo.avatar,
      });
    };

    const handleClose = (action: any) => {
      return new Promise((resolve) => {
        if (action === "confirm") {
          return resolve(false);
        } else {
          return resolve(true);
        }
      });
    };

    const handleJoinAI = async () => {
      MySender.getInstance().sendMsg(MsgCommand.JOIN_ROOM, { roomNo: "100" });
    };

    const open = () => {
      state.chatFlag = !state.chatFlag;
      state.activeChatClass = "shake";
      setTimeout(() => {
        state.activeChatClass = "";
      }, 1000);
    };

    const handleSyncMember = () => {};

    const handleSet = () => {
      state.setFlag = !state.setFlag;
    };

    const getUserInfo = async () => {
      let res = await getUser();
      if (res.status == 0) {
        state.userInfo = res.data;
        store.userInfo = res.data;
        openSocket(state.userInfo);
      } else {
        ElMessage.error(res.message);
      }
    };

    const handleJoin = () => {
      MySender.getInstance().sendMsg(MsgCommand.JOIN_ROOM, state.joinForm);
      setTimeout(() => {
        state.joinFlag = false;
      }, 100);
    };

    onMounted(() => {
      getUserInfo();
    });

    return {
      ...toRefs(state),
      ...toRefs(chatStatus),
      openSocket,
      handleAdd,
      handleJoin,
      handleJoinAI,
      handleLogin,
      handleSyncMember,
      store,
      open,
      handleSet,
      handleLeave,
      handleClose,
    };
  },
});
</script>
<style lang="less" scoped>
.room-box {
  width: 100%;
  height: calc(100vh - 64px);
  padding: 10px 16px;
  display: flex;
  flex-direction: column;

  &-btns {
    height: 30%;
  }

  &-logo {
    flex: 1;
    position: relative;
    overflow: hidden;
  }

  &-bg {
    position: absolute;
    bottom: 0px;
    width: 100%;
    left: 0px;
    z-index: -1;
  }
}
.chat-set {
  display: flex;
  flex-direction: column;
  justify-content: center;
  &-head {
    text-align: center;
  }
}

.person-info-box {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  span {
    font-size: 14px;
    color: #666666;
    line-height: 20px;
  }
}
</style>
      